<template>
  <div>
    <div class="center">
<!--      <div class="settime">-->
<!--        还剩：{{sec}} 秒-->
<!--      </div>-->
      <div v-if="finish" class="finish">
      </div>
      <div id="recording-player"></div>
      <div v-if="isEnable">
        <video autoplay :src="bloburl" controls></video>
<!--        <button @click="upload">上传</button>-->
      </div>
      <span id="btn-start-recording" class="play">
<!--        <span :class="platStatus?'stop': 'start'">录制</span>-->
      </span>
<!--      <button class="back" @click="$router.back(-1)">返回</button>-->
      <div id="save-to-disk" class="save">
<!--        <button   @click="save">下载</button>-->
<!--        <button  @click="play" >播放</button>-->
      </div>
    </div>

  </div>
</template>

<script>
import Utils from "../../../assets/js/util";
import RecordRTC from 'recordrtc'
import {clearInterval} from "timers";

export default {
  data() {
    return {
      winWidth: window.innerWidth,
      platStatus: false, //按钮显示‘开始’
      saveVideo: false,
      sec: 10,
      bloburl: '',
      interval: '',
      finish: false,
      isEnable: false,
      stop: false,
      i: 0
    }
  },
  created(){

  },
  mounted(){
    console.log(this.winWidth)
    const that = this;
    var video = document.createElement('video');
    video.controls = true;
    video.width = 400
    var mediaElement = getHTMLMediaElement(video, {
      buttons: ['full-screen', 'take-snapshot'],
      showOnMouseEnter: false,
      width: 500,
    });

    document.getElementById('recording-player').appendChild(video);
    var div = document.createElement('section');
    mediaElement.media.parentNode.appendChild(div);
    div.appendChild(mediaElement.media);
    var recordingPlayer = mediaElement.media;
    var btnStartRecording = document.querySelector('#btn-start-recording');
    var saveRecording = document.querySelector('#save-to-disk');
    var mimeType = 'video/webm';
    var fileExtension = 'webm';
    var recorderType = null;
    var type = 'video';
    var videoBitsPerSecond = null;
    var button = btnStartRecording;

    // 标记 1 获取网址
    function getURL(arg) {
      var url = arg;
      var str = typeof(arg);

      if(str === 'string'){
        that.finish = true;
      }
      that.bloburl = url;

      // 转成base64编码
      fetch(url).then(data=>{
        return data.blob();
      }).then(blob=>{
        let reader = new window.FileReader()
        reader.onloadend = function() {
          const data = reader.result
          // 编码文件信息 传送 urlData => reply.vue
          that.i =  that.i+1
          if (that.i===2){
            Utils.$emit('urlData',data)
            that.i = 0
          }
        }
        // 读取数据URL
        reader.readAsDataURL(blob)
      })
    }

    // 标记 2 设置视频网址
    function setVideoURL(arg, forceNonImage) {
      var url = getURL(arg);
      var parentNode = recordingPlayer.parentNode;
      parentNode.removeChild(recordingPlayer);
      parentNode.innerHTML = '';
      var elem = 'video';
      recordingPlayer = document.createElement(elem);
      if(arg instanceof MediaStream) {
        recordingPlayer.muted = true;
      }

      recordingPlayer.addEventListener('loadedmetadata', function() {
        if(navigator.userAgent.toLowerCase().indexOf('android') === -1) return;
        // android
        setTimeout(function() {
          if(typeof recordingPlayer.play === 'function') {
            recordingPlayer.play();
          }
        }, 2000);
      }, false);
      recordingPlayer.poster = '';
      if(arg instanceof MediaStream) {
        recordingPlayer.srcObject = arg;
      } else {
        recordingPlayer.src = url;
      }
      if(typeof recordingPlayer.play === 'function') {
        recordingPlayer.play();
      }

      recordingPlayer.addEventListener('ended', function() {
        url = getURL(arg);
        if(arg instanceof MediaStream) {
          recordingPlayer.srcObject = arg;
        }else {
          recordingPlayer.src = url;
        }
      });
      parentNode.appendChild(recordingPlayer);
    }

    // 标记 4 录制按钮 媒体捕获回调
    button.mediaCapturedCallback = function() {
      var options = {
        type: type,
        mimeType: mimeType,
        getNativeBlob: true, // enable it for longer recordings
        video: recordingPlayer // 录音播放器
      };
      options.ignoreMutedMedia = false; // 忽略静音媒体
      button.recordRTC = RecordRTC(button.stream, options);
      button.recordingEndedCallback = function(url) {
        // 标记 4
        setVideoURL(url);
      };
      // 开始录音
      button.recordRTC.startRecording();
    }

    // 标记 5 通用配置 初始化
    var commonConfig = {
      onMediaCaptured: function(stream) {
        // that.finish = false;
        button.stream = stream;
        if(button.mediaCapturedCallback) {
          button.mediaCapturedCallback();
        }

        // button.innerHTML = "停止";
        button.disabled = false;
        that.platStatus = true;
        // that.interval = setInterval(() => {
        //   that.sec--;
        //   if (that.sec <= 0) {
        //     clearInterval(that.interval);
        //     btnStartRecording.onclick();
        //   }
        // }, 1000);
      },

      // 标记 6 媒体停止
      onMediaStopped: function() {
        // button.innerHTML = "开始";
        that.platStatus = false;
        that.sec = 10
        if(!button.disableStateWaiting) {
          button.disabled = false;
        }

        // 开始下载
        // location.href=that.bloburl
        // 地址传递 url
        Utils.$emit('url',that.bloburl);

        // start
        clearInterval(that.interval);
        if(that.platStatus === true) {
          button.disabled = true;
          button.disableStateWaiting = true;
          setTimeout(function() {
            button.disabled = false;
            button.disableStateWaiting = false;
          }, 2000);
          // button.innerHTML = "开始";
          that.platStatus = false;
          that.saveVideo = true;
          if(button.recordRTC) {
            if(button.recordRTC.length) {
              button.recordRTC[0].stopRecording(function(url) {
                if(!button.recordRTC[1]) {
                  button.recordingEndedCallback(url);
                  stopStream();
                  saveToDiskOrOpenNewTab(button.recordRTC[0]);
                  return;
                }
                button.recordRTC[1].stopRecording(function(url) {
                  button.recordingEndedCallback(url);
                  stopStream();
                });
              });
            }
            else {
              button.recordRTC.stopRecording(function(url) {
                button.recordingEndedCallback(url);
                saveToDiskOrOpenNewTab(button.recordRTC);
                stopStream();
              });
            }
          }
          return;
        }
        captureAudioPlusVideo(commonConfig);
      },

      // 标记 7 媒体捕获失败
      onMediaCapturingFailed: function(error) {
        if(error.toString().indexOf('no audio or video tracks available') !== -1) {
          alert('RecordRTC failed to start because there are no audio or video tracks available.');
        }

        if(DetectRTC.browser.name === 'Safari') return;

        if(error.name === 'PermissionDeniedError' && DetectRTC.browser.name === 'Firefox') {
          alert('Firefox requires version >= 52. Firefox also requires HTTPs.');
        }

        commonConfig.onMediaStopped();
      }
    };

    // 标记 8 捕获用户媒体
    function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
      if(mediaConstraints.video === true) {
        mediaConstraints.video = {};
      }

      // 获取用户媒体
      navigator.mediaDevices.getUserMedia(mediaConstraints).then(function(stream) {
        successCallback(stream);
        if (!that.stop){
          // 标记2 设置视频网址
          setVideoURL(stream, true);
        }
      }).catch(function(error) {
        if(error && error.name === 'ConstraintNotSatisfiedError') {
          alert('Your camera or browser does NOT supports selected resolutions or frame-rates. \n\nPlease select "default" resolutions.');
        }
        errorCallback(error);
      });
    }

    // 标记 9 添加流停止监听器
    function addStreamStopListener(stream, callback) {
      var streamEndedEvent = 'ended';
      if ('oninactive' in stream) {
        streamEndedEvent = 'inactive';
      }
      stream.addEventListener(streamEndedEvent, function() {
        callback();
        callback = function() {};
      }, false);
      stream.getAudioTracks().forEach(function(track) {
        track.addEventListener(streamEndedEvent, function() {
          callback();
          callback = function() {};
        }, false);
      });
      stream.getVideoTracks().forEach(function(track) {
        track.addEventListener(streamEndedEvent, function() {
          callback();
          callback = function() {};
        }, false);
      });
    }

    // 标记 10 捕获音频加视频
    function captureAudioPlusVideo(config) {
      that.finish = false;
      // that.stop == true ? 'stop' : 'start'
      if (!that.stop){
        // captureUserMedia 执行 8
        captureUserMedia({video: true, audio: true}, function(audioVideoStream) {
          config.onMediaCaptured(audioVideoStream); // 执行 5（调起摄像头）
          if(audioVideoStream instanceof Array) {
            audioVideoStream.forEach(function(stream) {
              //执行 9
              addStreamStopListener(stream, function() {
                config.onMediaStopped(); // 执行 6
              });
            });
            return;
          }
          // 添加流停止监听器
          addStreamStopListener(audioVideoStream, function() {
            config.onMediaStopped(); // 执行 6
          });
        }, function(error) {
          config.onMediaCapturingFailed(error); // 执行 7
        });
      }
    }

    // 标记 11 停止流
    function stopStream() {
      if(button.stream && button.stream.stop) {
        button.stream.stop();
        button.stream = null;
      }

      if(button.stream instanceof Array) {
        button.stream.forEach(function(stream) {
          stream.stop();
        });
        button.stream = null;
      }

      videoBitsPerSecond = null;
      var html = 'Recording status: stopped';
      html += '<br>Size: ' + button.recordRTC.getBlob().size;
    }

    // 标记 12 获取文件名
    function getFileName(fileExtension) {
      var d = new Date().getTime();
      // var year = d.getUTCFullYear();
      // var month = d.getUTCMonth() + 1;
      // var date = d.getUTCDate();
      return 'RecordRTC-' + d + '.' + fileExtension;
    }

    // 标记 13 保存到磁盘或打开新标签页
    function saveToDiskOrOpenNewTab(recordRTC) {
      // 12 获取文件名
      var fileName = getFileName(fileExtension);
      saveRecording.onclick = function(event) {
        if(!recordRTC) return alert('No recording found.');
        var file = new File([recordRTC.getBlob()], fileName, {
          type: mimeType
        });
        console.log("file******" + file)
        // axios.post("/api/resume/upload/uplodeFile",file).then(res=>{
        //   if(res=="111"){
        //     alert(1111)
        //   }
        // })

        // that.$store.commit("changeAndroidVideo", file);
        // that.$router.back(-1);
        // invokeSaveAsDialog(file, file.name);
      }
    }

    // 标记 14 开始录音 操作录像
    btnStartRecording.onclick = function(event) {
      clearInterval(that.interval);
      if(that.platStatus === true) {
        button.disabled = true;
        button.disableStateWaiting = true;
        setTimeout(function() {
          button.disabled = false;
          button.disableStateWaiting = false;
        }, 2000);
        // button.innerHTML = "开始";
        that.platStatus = false;
        that.saveVideo = true;
        if(button.recordRTC) {
          if(button.recordRTC.length) {
            button.recordRTC[0].stopRecording(function(url) {
              if(!button.recordRTC[1]) {
                button.recordingEndedCallback(url);
                stopStream();
                saveToDiskOrOpenNewTab(button.recordRTC[0]);
                return;
              }
              button.recordRTC[1].stopRecording(function(url) {
                button.recordingEndedCallback(url);
                stopStream();
              });
            });
          }
          else {
            button.recordRTC.stopRecording(function(url) {
              button.recordingEndedCallback(url);
              saveToDiskOrOpenNewTab(button.recordRTC);
              stopStream();
            });
          }
        }
        return;
      }
      captureAudioPlusVideo(commonConfig);
    }

    // 接收命令 start next 先关闭录像再录像
    Utils.$on('start', function (msg) {
      clearInterval(that.interval);
      console.log(that.platStatus)
      if(that.platStatus === true) {
        button.disabled = true;
        button.disableStateWaiting = true;
        setTimeout(function() {
          button.disabled = false;
          button.disableStateWaiting = false;
        }, 2000);
        // button.innerHTML = "开始";
        that.platStatus = false;
        that.saveVideo = true;
        if(button.recordRTC) {
          if(button.recordRTC.length) {
            button.recordRTC[0].stopRecording(function(url) {
              if(!button.recordRTC[1]) {
                button.recordingEndedCallback(url);
                stopStream();
                saveToDiskOrOpenNewTab(button.recordRTC[0]);
                return;
              }
              button.recordRTC[1].stopRecording(function(url) {
                button.recordingEndedCallback(url);
                stopStream();
              });
            });
          }
          else {
            button.recordRTC.stopRecording(function(url) {
              button.recordingEndedCallback(url);
              saveToDiskOrOpenNewTab(button.recordRTC);
              stopStream();
            });
          }
        }
        return;
      }
      captureAudioPlusVideo(commonConfig);
    })

    // 接收命令 stop 停止录像
    Utils.$on('stop', function (msg) {
      that.stop = true;
      clearInterval(that.interval);
      console.log(that.platStatus)
      if(that.platStatus === true) {
        button.disabled = true;
        button.disableStateWaiting = true;
        setTimeout(function() {
          button.disabled = false;
          button.disableStateWaiting = false;
        }, 2000);
        // button.innerHTML = "开始";
        that.platStatus = false;
        that.saveVideo = true;
        if(button.recordRTC) {
          if(button.recordRTC.length) {
            button.recordRTC[0].stopRecording(function(url) {
              if(!button.recordRTC[1]) {
                button.recordingEndedCallback(url);
                stopStream();
                saveToDiskOrOpenNewTab(button.recordRTC[0]);
                return;
              }
              button.recordRTC[1].stopRecording(function(url) {
                button.recordingEndedCallback(url);
                stopStream();
              });
            });
          }
          else {
            button.recordRTC.stopRecording(function(url) {
              button.recordingEndedCallback(url);
              saveToDiskOrOpenNewTab(button.recordRTC);
              stopStream();
            });
          }
        }
        return;
      }
      captureAudioPlusVideo(commonConfig);
    })

    // 使用即执行 调起多媒体开始录制
    clearInterval(that.interval);
    console.log(that.platStatus)
    if(that.platStatus === true) {
      button.disabled = true;
      button.disableStateWaiting = true;
      setTimeout(function() {
        button.disabled = false;
        button.disableStateWaiting = false;
      }, 2000);
      // button.innerHTML = "开始";
      that.platStatus = false;
      that.saveVideo = true;
      if(button.recordRTC) {
        if(button.recordRTC.length) {
          button.recordRTC[0].stopRecording(function(url) {
            if(!button.recordRTC[1]) {
              button.recordingEndedCallback(url);
              stopStream();
              saveToDiskOrOpenNewTab(button.recordRTC[0]);
              return;
            }
            button.recordRTC[1].stopRecording(function(url) {
              button.recordingEndedCallback(url);
              stopStream();
            });
          });
        }
        else {
          button.recordRTC.stopRecording(function(url) {
            button.recordingEndedCallback(url);
            saveToDiskOrOpenNewTab(button.recordRTC);
            stopStream();
          });
        }
      }
      return;
    }
    captureAudioPlusVideo(commonConfig);

  },
  methods: {
    save(){
      alert(15)
      if(this.bloburl!=null && this.bloburl!=='' && typeof this.bloburl=="string"){
        alert(this.bloburl)
        location.href=this.bloburl;
      }else{
        alert("请先拍摄视频");
      }

    },
    play(){
      alert(16)
      if(this.bloburl!=null && this.bloburl!==''){
        this.isEnable = true;

      }else{
        alert("请先拍摄视频");
      }
    }
  }
};
</script>
<style scoped>
video {
  width: 200px;
}
</style>
